package com.example.jussi.socketdemo;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
    EditText content, ip;
    TextView textView;
    String result;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 0x01){
                textView.setText(result);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        content = (EditText) findViewById(R.id.editText);
        ip = (EditText) findViewById(R.id.editText2);
        textView = (TextView) findViewById(R.id.textView2);
    }

    public void send(View hhView){
        Log.d("-------------", "send: ");
        new Thread(){
            @Override
            public void run() {
                Socket socket = null;
                InputStream inputStream = null;
                OutputStream outputStream = null;
                try {
                    Log.d("-------------", "run: ");
                    socket = new Socket(ip.getText().toString(), 30003);
                    inputStream = socket.getInputStream();
                    outputStream = socket.getOutputStream();
                    PrintStream printStream = new PrintStream(outputStream);
                    printStream.println(content.getText().toString());
                    //Log.d("--------------", content.getText().toString());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
                    result = reader.readLine();
                    //Log.d("-------------------", result);
                    handler.sendEmptyMessage(0x01);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if(socket != null){
                            socket.close();
                        }
                        if(inputStream != null){
                            inputStream.close();
                        }
                        if(outputStream != null){
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}
